﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading;
using Common.Utilities;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.Entities.MasterData
{
    /// <summary>
    /// 
    /// </summary>
    [Serializable]
    public class FieldDistributionWorker:IWorker 
    {
        #region Implementation of IWorker

        public event WorkerStarted WorkerStartedEvent;
        public event WorkerFinished WorkerFinishedEvent;
        public event WorkerHasError WorkerErredEvent;
        public event WorkerCancelled WorkerCancelledEvent;
        public event WorkerStatusChanged WorkerStatusChangedEvent;

        private Thread workerThread;
        private FieldDistributionInstruction instruction;
        private FieldDistributionOutput output;
        private RunContext _Context;
        private Guid _TicketID;
        private string _WorkflowName;
        private string _ComponentName;

        /// <summary>
        /// 
        /// </summary>
        public string ComponentName
        {
            get { return _ComponentName; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string WorkflowName
        {
            get { return _WorkflowName; }
        }

        /// <summary></summary>
        public Thread WorkerThread
        {
            get { return workerThread; }
        }
        /// <summary></summary>
        public InstructionBase Instruction
        {
            get { return instruction; }
        }
        /// <summary></summary>
        public ResultBase Output
        {
            get { return output; }
        }
        /// <summary></summary>
        public Type ComponentType
        {
            get { return typeof(FieldDistributionComponent); }
        }
        /// <summary></summary>
        public RunContext Context
        {
            get { return _Context; }
            set { _Context = value; }
        }
        /// <summary></summary>
        public void SetInstruction(Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._TicketID = ticketGuid;
            this.instruction = (FieldDistributionInstruction)request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }
        /// <summary></summary>
        public void SetInstruction(RunContext context, Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._TicketID = ticketGuid;
            this.instruction = (FieldDistributionInstruction)request;
            this._Context = context;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }
        /// <summary></summary>
        public void DoWork()
        {
            if (this.WorkerStartedEvent != null)
            {
                this.WorkerStartedEvent(this._TicketID, this, this.GetType(), this.instruction);
            }
            this.workerThread = Thread.CurrentThread;
            this.CalculateFieldDistribution();
        }
        /// <summary></summary>
        public void DoWorkAsync()
        {
            if (this.WorkerStartedEvent != null)
            {
                this.WorkerStartedEvent(this._TicketID, this, this.GetType(), this.instruction);
            }
            this.workerThread = new Thread(new ThreadStart(this.CalculateFieldDistribution));
            this.workerThread.Start();
        }
        /// <summary></summary>
        public void CancelWork()
        {
            if (this.workerThread != null && this.workerThread.IsAlive)
            {
                this.workerThread.Abort();
                this.workerThread.Join();

                if (this.WorkerCancelledEvent != null)
                {
                    this.WorkerCancelledEvent(this._TicketID, this.GetType(), this.instruction);
                }
            }
        }

        #endregion

        #region work
        private void CalculateFieldDistribution()
        {
            SqlConnection conn=new SqlConnection(this.instruction.ConnStr);
            try
            {
                int recordCount = DbUtil.GetTableRecordCount(DataProviderType.MSSQL,
                                                             this.instruction.ConnStr, this.instruction.SchemaName,
                                                             this.instruction.TableName);
                conn.Open();
                SqlCommand cmd = conn.CreateCommand();
                double gini = 0;
                Dictionary<object,double> distribution=new Dictionary<object, double>();
                Dictionary<object, Dictionary<object, double>> recordDistribution =
                    new Dictionary<object, Dictionary<object, double>>();

                if(!string.IsNullOrEmpty(this.instruction.BinField))
                {
                    string sql1 =
                        @"
select 
    {0}, 
    sum(cast(isnull({1},0) as float)) as freq 
from 
    {2}.{3} 
where {0} is not null 
group by {0}
order by sum({1}) asc";
                    sql1 = string.Format(sql1, this.instruction.BinField, this.instruction.FieldName,
                                         this.instruction.SchemaName, this.instruction.TableName);
                    cmd.CommandText = sql1;
                    SqlDataReader reader = cmd.ExecuteReader();
                    while(reader.Read())
                    {
                        object key = reader[this.instruction.BinField];
                        double freq = double.Parse(reader["freq"].ToString());
                        distribution.Add(key, freq);
                    }
                    reader.Close();
                    string sql2 = @"select {0},{1},isnull({2},0) from {3},{4}";
                    sql2 = string.Format(
                        sql2, this.instruction.PkField, this.instruction.BinField,
                        this.instruction.FieldName, this.instruction.SchemaName,
                        this.instruction.TableName);
                    cmd.CommandText = sql2;
                    Dictionary<object,double> giniMeasures=new Dictionary<object, double>();
                    reader = cmd.ExecuteReader();
                    while(reader.Read())
                    {
                        object pk = reader[this.instruction.PkField];
                        giniMeasures.Add(pk, 0);
                        object binValue = reader[this.instruction.BinField];
                        double numValue = double.Parse(reader[this.instruction.FieldName].ToString());
                        numValue = numValue*recordCount/distribution[binValue];
                        if(recordDistribution.ContainsKey(binValue))
                        {
                            Dictionary<object, double> fieldDist = recordDistribution[binValue];
                            fieldDist.Add(pk,numValue);
                            recordDistribution[binValue] = fieldDist;
                        }
                        else
                        {
                            Dictionary<object,double> fieldDist=new Dictionary<object, double>();
                            fieldDist.Add(pk,numValue);
                            recordDistribution.Add(binValue, fieldDist);
                        }
                    }
                    reader.Close();

                    object[] distBinValues = new object[distribution.Count];
                    distribution.Keys.CopyTo(distBinValues, 0);
                    foreach (object pk in giniMeasures.Keys)
                    {
                        double[] cumulative_sums = new double[recordDistribution.Count];
                        double sum = 0;
                        for (int i = 0; i < distBinValues.Length; i++)
                        {
                            sum += recordDistribution[pk][distBinValues[i]];
                            cumulative_sums[i] = sum;
                        }
                        double[] freqs=new double[recordDistribution.Count];
                        for(int i=0; i<distBinValues.Length;i++)
                        {
                            double freq = recordDistribution[pk][distBinValues[i]];
                            freq = freq/sum;
                            freqs[i] = freq;
                        }

                    }

                }
   

                this.output=new FieldDistributionOutput(this.instruction.OwnerComponentID,this._TicketID,gini);
                if (this.WorkerFinishedEvent != null)
                    this.WorkerFinishedEvent(this._TicketID, this.GetType(), this.instruction, this.output);
            }
            catch(Exception ex)
            {
                if (this.WorkerErredEvent != null)
                    this.WorkerErredEvent(this._TicketID, this.GetType(), this.instruction, ex.ToString(), true);
            }
        }
        #endregion
    }
}
